// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain, dialog, MenuItem, Menu} = require('electron')
const path = require('path')
const isDev = require('electron-is-dev')
const autoUpdater = require("electron-updater").autoUpdater;
let mainWindow; //mainWindow主窗口

let express = require('express');
let ejs = require('ejs');
let logger = require('morgan');
let app2 = express();

let template = [{
    label: '查看',
    submenu: [{
        label: '重载',
        accelerator: 'CmdOrCtrl+R',
        click: (item, focusedWindow) => {
            if (focusedWindow) {
                // 重载之后, 刷新并关闭所有之前打开的次要窗体
                if (focusedWindow.id === 1) {
                    BrowserWindow.getAllWindows().forEach(win => {
                        if (win.id > 1) win.close()
                    })
                }
                focusedWindow.reload()
            }
        }
    }, {
        label: '切换全屏',
        accelerator: (() => {
            if (process.platform === 'darwin') {
                return 'Ctrl+Command+F'
            } else {
                return 'F11'
            }
        })(),
        click: (item, focusedWindow) => {
            if (focusedWindow) {
                focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
            }
        }
    }, {
        label: '切换开发者工具',
        accelerator: (() => {
            if (process.platform === 'darwin') {
                return 'Alt+Command+I'
            } else {
                return 'Ctrl+Shift+I'
            }
        })(),
        click: (item, focusedWindow) => {
            if (focusedWindow) {
                focusedWindow.toggleDevTools()
            }
        }
    }]
}, {
    label: '窗口',
    role: 'window',
    submenu: [{
        label: '最小化',
        accelerator: 'CmdOrCtrl+M',
        role: 'minimize'
    }, {
        label: '关闭',
        accelerator: 'CmdOrCtrl+W',
        role: 'close'
    }, {
        type: 'separator'
    }, {
        label: '重新打开窗口',
        accelerator: 'CmdOrCtrl+Shift+T',
        enabled: false,
        key: 'reopenMenuItem',
        click: () => {
            app.emit('activate')
        }
    }]
}]

function addUpdateMenuItems(items, position) {
    if (process.mas) return

    const version = app.getVersion()
    let updateItems = [{
        label: `版本 ${version}`,
        enabled: false
    }
        // , {
        //     label: '检查更新',
        //     key: 'checkForUpdate',
        //     click: () => {
        //         console.log('检查更新')
        //         autoUpdater.checkForUpdates();
        //     }
        // }
    ]

    items.splice.apply(items, [position, 0].concat(updateItems))
}

const helpMenu = template[template.length - 1].submenu
addUpdateMenuItems(helpMenu, 0)


function createWindow() {
    console.log('ready')
    // Create the browser window.
    mainWindow = new BrowserWindow({
        minWidth: 1300,
        minHeight: 740,
        icon: './favicon.ico',
        center: true,
        webPreferences: {
            devTools: true, //是否开启 DevTools
            nodeIntegration: true,
            contextIsolation: false,
            hardwareAcceleration:true,
        },
        show: false
    })
    console.log('isDev', isDev)
    // and load the index.html of the app.

    if (isDev) {
        // mainWindow.loadURL("http://localhost:3000/");
        // // Open the DevTools.
        // mainWindow.webContents.openDevTools()


        app2.use(express.static(path.join(__dirname, '.')));
// view engine setup for html
        app2.set('views', path.join(__dirname, '.'));
        app2.engine('.html', ejs.__express);
        app2.set('view engine', 'html');

// view engine setup for ejs
// app2.set('views', path.join(__dirname, 'views'));
// app2.set('view engine', 'ejs');


        app2.use(logger('dev'));

        app2.get('/*', function(req, res, next) {
            res.render('index');
        });

        let server = app2.listen(15326,'0.0.0.0', function () {
            let host = server.address().address;
            let port = server.address().port;
            console.log('WATER APP listening at http://%s:%s', host, port);
            mainWindow.loadURL('http://localhost:15326/logs')
        });


    } else {


        app2.use(express.static(path.join(__dirname, '.')));
// view engine setup for html
        app2.set('views', path.join(__dirname, '.'));
        app2.engine('.html', ejs.__express);
        app2.set('view engine', 'html');

// view engine setup for ejs
// app2.set('views', path.join(__dirname, 'views'));
// app2.set('view engine', 'ejs');


        app2.use(logger('dev'));

        app2.get('/*', function(req, res, next) {
            res.render('index');
        });

        let server = app2.listen(15326,'127.0.0.1', function () {
            let host = server.address().address;
            let port = server.address().port;
            console.log('WATER APP listening at http://%s:%s', host, port);
            mainWindow.loadURL('http://127.0.0.1:15326/logs')
            // mainWindow.loadURL('http://www.yanhuangxueyuan.com/threejs/examples/#webgl_animation_keyframes')

        });

        // const http = require('http');
        // const server = http.createServer((request, response) => {
        //     // You pass two more arguments for config and middleware
        //     // More details here: https://github.com/zeit/serve-handler#options
        //     return handler(request, response, {
        //         public: 'resources/app.asar/build',
        //     });
        // })
        // server.listen(15326, () => {
        //     mainWindow.loadURL('http://localhost:15326/home')
        // });
        // mainWindow.loadURL(url.format({
        //     pathname: path.join(__dirname, './../build/index.html'), // 修改
        //     protocol: 'file:',



        //     slashes: true
        // }))
    }
    const menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)

    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        mainWindow = null
    })
    mainWindow.once('ready-to-show', () => {
        mainWindow.maximize();
        mainWindow.show();
        mainWindow.webContents.send('ping', 'whoooooooh!');
        updateHandle() //更新需要在页面显示之后，否则不能打印出相应的内容
        // createMbus()
    })





    //提示
    ipcMain.on('open-dialog', (e, message) => {
        openDialog(message)
    });




}

function openDialog(message) {
    dialog.showMessageBox(mainWindow, {
        type: message.type,
        title: message.title,
        message: message.message,
    })
}
console.log('before disableHardwareAcceleration')
// app.disableHardwareAcceleration() 禁用硬件加速，有3D不能使用
console.log('after disableHardwareAcceleration')
app.on('ready', createWindow)

app.on('window-all-closed', function () {
    console.log('process.platform', process.platform) //平台
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function () {
    console.log('activate')
    if (mainWindow === null) createWindow()
})


function updateHandle() {
    console.log('updateHandle')
    let message = {
        error: '检查更新出错',
        checking: '正在检查更新……',
        updateAva: '检测到新版本，正在下载……',
        updateNotAva: '现在使用的就是最新版本，不用更新',
    };

    autoUpdater.setFeedURL('http://182.61.56.51:4009/electron/');
    autoUpdater.autoDownload = false //不强制下载
    autoUpdater.on('error', function (error) {
        sendUpdateMessage({
            type: 'error',
            message: message.error
        })
    });
    autoUpdater.on('checking-for-update', function () {
        sendUpdateMessage({
            type: 'info',
            message: message.checking
        })
    });
    autoUpdater.on('update-available', function (info) {
        sendUpdateMessage({
            type: 'info',
            message: message.updateAva
        })
        autoUpdater.downloadUpdate().then(res => { //下载更新
            sendUpdateMessage({
                type: 'success',
                message: '下载更新'
            })
        });
    });
    autoUpdater.on('update-not-available', function (info) {
        sendUpdateMessage({
            type: 'success',
            message: message.updateNotAva
        })
    });

    // 更新下载进度事件
    autoUpdater.on('download-progress', function (progressObj) {
        sendUpdateMessage({
            type: 'info',
            message: '检测到新版本，正在下载: ' + Number(progressObj.percent).toFixed(2) + " %"
        })
    })

    autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
        sendUpdateMessage({
            type: 'success',
            message: '下载完成，开始更新'
        })
        autoUpdater.quitAndInstall();

        // ipcMain.on('isUpdateNow', (e, arg) => { //监听渲染发送过来的消息，比如用户按确定键后再开始跟新
        //   console.log("开始更新");
        //   sendUpdateMessage('开始更新')
        //   //some code here to handle event
        //   autoUpdater.quitAndInstall();
        // });
        // mainWindow.webContents.send('isUpdateNow') //像渲染层发送消息

    });

    ipcMain.on('UpdateNow', (e, arg) => { //ipcMain主进程监听渲染发送过来的消息，比如用户按确定键后再开始更新
        console.log('用户点击查询更新')
        //如果不是手动更新，将checkForUpdates提取到外面直接执行。
        autoUpdater.checkForUpdates(); //向服务端查询现在是否有可用的更新。在调用这个方法之前，必须要先调用 setFeedURL。
    });

}

function sendUpdateMessage(msg) {
    mainWindow.webContents.send('updateMessage', msg)
}

